/**
 * 版本更新的类，用于2.0升级3.0使用
 */
import { FileUtil } from "../../utils/FileUtil";
import { UserResource } from "../sqlite/model/UserResource";
import { SqlLibUser } from "../sqlite/service/SqlLibUser";
import { SqlLib } from "../sqlite/SqlLib";
import { UUIDUtil } from "../../utils/UUIDUtil";
import { SqlLibBook } from "../sqlite/service/SqlLibBook";
import { DownloadCenter } from "./DownloadCenter";
import { ThumbDownloader } from "./ThumbDownloader";
import { GeneratorFactory } from "../executor/GeneratorFactory";
import { GeneratorExecutor } from "../executor/GeneratorExecutor";
import { SingleDownloadTask } from "./SingleDownloadTask";

const path = require('path');
const fs = require('fs');

export class VersionUpdater {

    constructor(request) {
        this.request = request;
        this.dataDir = path.dirname(window.$DBDIR);
        // this.dataDir = "C:\\Program Files (x86)\\美丽科学\\html\\";
        // this.resourceDir = path.dirname(this.dataDir);
        // let htmlDir = path.dirname(this.resourceDir);
        // this.htmlDir = path.join(htmlDir, "html");
        this.oldVersionBak = path.join(this.dataDir, "resc", "courseware", "2101007.bsr");
        console.log("oldVersionBak", this.oldVersionBak);
    }

    isRequireRefresh () {
        return fs.existsSync(this.oldVersionBak);
    }

    refreshDB (callback, progressCallback) {
        let _this = this;
        let oldBsr = FileUtil.readFile(_this.oldVersionBak);
        oldBsr = JSON.parse(oldBsr);
        console.log("oldBsr", oldBsr);

        if (oldBsr instanceof Array) {
            let sqlLib = SqlLib.getInstance(window.$DBDIR);
            let user = SqlLibUser.queryCurrentUser(sqlLib);
            let polyvVideos = [];
            let pptThumbs = [];
            //1.首先拷贝zip文件，弃用了，由安装包去干
            // try{
            //     FileUtil.copyDirectory(path.join(_this.htmlDir, "resc"), path.join(_this.dataDir, "resc"), true);
            // }catch (e) {
            //     console.error(e);
            // }

            this.request.getFourUpLessonIds({}).then(response => {
                let lessonIds = [];
                if (response.code == "0") {
                    lessonIds = response.returnValue.lessonIds;
                }
                let requestProm = [];
                //2.刷新DB的数据
                oldBsr.forEach(lesson => {
                    if (lesson.data && !lessonIds.includes(lesson.id)) {//去除四上的课时
                        console.log("需要更新的课时id", lesson.id)
                        let resCoursewaresVOList = lesson.data.resCoursewaresVOList;
                        let resourceVOList = lesson.data.resourceVOList;

                        let result = [];
                        let resultBsr = [];
                        if (resCoursewaresVOList && resCoursewaresVOList.length > 0) {
                            resCoursewaresVOList.forEach((courseware, index) => {
                                let courseObj = {
                                    id: courseware.id,
                                    name: courseware.title,
                                    resType: "PPT",
                                    tag: 0, //0 - 美丽科学；1 - twig
                                    thumb: courseware.thumb,
                                    downloadInfo: {
                                        FileName: courseware.id + ".ppt",
                                        FileType: "courseware",
                                        TaskId: courseware.id,
                                        Url: courseware.url
                                    }
                                };
                                if (index === 0) {
                                    courseObj.isDefault = "1";
                                } else {
                                    courseObj.isDefault = "0";
                                }
                                if (_this.checkResourceExsist(courseObj)) {
                                    result.push(courseObj);
                                    resultBsr.push({
                                        metaId: courseware.id,
                                        metaType: "courseware"
                                    });
                                    if (courseware.thumb.startsWith("https://")) {
                                        let thumbStr = courseware.thumb.match(/static.kquestions.com\/(\S*)\?/)[1];
                                        pptThumbs.push({
                                            id: courseware.id,
                                            thumb: courseware.thumb,
                                            type: "courseware",
                                            thumbStr: thumbStr
                                        });
                                    }
                                }
                            });
                        }
                        if (resourceVOList && resourceVOList.length > 0) {
                            let quizes = [];
                            resourceVOList.forEach(resource => {
                                let info = {
                                    id: resource.resMetaInfoVO.meta_id,
                                    name: resource.name,
                                    resType: "课时资源 | " + DownloadCenter.getInstance().resTypeToName(resource.resMetaInfoVO.res_type),
                                    tag: resource.tag === "twig" ? 1 : 0, //0 - 美丽科学；1 - twig
                                    thumb: resource.resMetaInfoVO.thumb,
                                    brief: resource.brief ? resource.brief : "",
                                    intro: resource.intro ? resource.intro : "",
                                    scenarios: resource.scenarios ? resource.scenarios : "",
                                    downloadInfo: {
                                        TaskId: resource.resMetaInfoVO.meta_id,
                                        FileType: DownloadCenter.getInstance().resTypeToEnName(resource.resMetaInfoVO.res_type),
                                        FileName: DownloadCenter.getInstance().resTypeToEnName(resource.resMetaInfoVO.res_type) === "PolyvVideo" ? resource.resMetaInfoVO.meta_id : resource.resMetaInfoVO.meta_id + ".zip",
                                        Url: resource.resMetaInfoVO.zip_url ? DownloadCenter.getInstance().constVar.global.cdnResourcePrefix + resource.resMetaInfoVO.zip_url : ""
                                    }
                                };
                                if (_this.checkResourceExsist(info)) {
                                    resultBsr.push({
                                        metaId: resource.resMetaInfoVO.meta_id,
                                        metaType: DownloadCenter.getInstance().resTypeToEnName(resource.resMetaInfoVO.res_type)
                                    });
                                    if (DownloadCenter.getInstance().resTypeToEnName(resource.resMetaInfoVO.res_type) === "Quiz") {
                                        quizes.push(info);
                                        if (info.thumb.startsWith("https://")) {
                                            let thumbStr = info.thumb.match(/static.kquestions.com\/(\S*)\?/)[1]
                                            pptThumbs.push({
                                                id: info.id,
                                                thumb: info.thumb,
                                                type: "Quiz",
                                                thumbStr: thumbStr
                                            });
                                        }
                                    } else {
                                        result.push(info);
                                    }
                                }
                            });
                            result = result.concat(quizes);
                        }
                        if (resultBsr.length > 0) {
                            let promise = new Promise(resolve => {
                                _this.request.getResourceInfoByResIds({ metaParamDTOS: resultBsr }).then(response => {
                                    if (response.code == "0") {
                                        let bsrResources = response.returnValue.resources;
                                        result.forEach((item, index) => {
                                            if (bsrResources[item.id]) {
                                                let bsr = bsrResources[item.id];
                                                bsr.brief = item.brief ? item.brief : "";
                                                bsr.intro = item.intro ? item.intro : "";
                                                bsr.scenarios = item.scenarios ? item.scenarios : "";
                                                item.downloadInfo.Bsr = JSON.stringify(bsr);
                                            }
                                            if (item.downloadInfo.FileType === "courseware") {
                                                item.downloadInfo.Bsr = JSON.stringify(item);
                                            }
                                            if (item.downloadInfo.FileType === "PolyvVideo") {
                                                polyvVideos.push(item.downloadInfo);
                                            }
                                            let userResource = new UserResource();
                                            userResource.id = UUIDUtil.uuid();
                                            userResource.userId = user.id;
                                            userResource.lessonId = lesson.id;
                                            userResource.resourceClassify = "2";
                                            userResource.resourceType = item.downloadInfo.FileType;
                                            userResource.sortIndex = index + 1;
                                            userResource.resourceId = item.id;
                                            userResource.resourceName = item.name;
                                            let bsr = item.downloadInfo.Bsr;
                                            if (bsr) {
                                                bsr = JSON.parse(bsr);
                                                if (bsr.isDefault) {
                                                    userResource.isDefault = bsr.isDefault;
                                                } else {
                                                    userResource.isDefault = "0"
                                                }
                                            } else {
                                                userResource.isDefault = "0"
                                            }
                                            userResource.resourceDescription = item.downloadInfo.Bsr;
                                            userResource.downloadStatus = "0";
                                            userResource.sortIndex = index + 1;
                                            SqlLibBook.updateOrInsertOneResource(sqlLib, userResource);
                                        });
                                    }
                                    resolve("success")
                                }).catch(err => { resolve("error") })
                            });
                            requestProm.push(promise);
                        }
                    }
                });

                //3.完善资源
                Promise.all(requestProm).then(response => {
                    if (pptThumbs.length > 0) {
                        let tempThumbs = [];
                        pptThumbs.forEach(thumbs => {
                            if (thumbs.thumbStr) {
                                tempThumbs.push(thumbs.thumbStr);
                            }
                        })
                        _this.request.getUrlByThumbs({ thumbs: tempThumbs }).then(response => {
                            if (response.code === "0") {
                                let thumbUrls = response.returnValue.thumbUrls;
                                pptThumbs.forEach(thumbs => {
                                    for (let i = 0;i < thumbUrls.length;i++) {
                                        let thumbStr = thumbUrls[i].match(/static.kquestions.com\/(\S*)\?/)[1];
                                        if (thumbs.thumbStr === thumbStr) {
                                            thumbs.thumb = thumbUrls[i];
                                            break;
                                        }
                                    }
                                })
                                console.log("下载的thumb数据pptThumbs", pptThumbs);
                                ThumbDownloader.downloadPptThumbs(pptThumbs);
                            }
                        });
                    }
                    if (polyvVideos.length > 0) {
                        console.log("polyvVideos", polyvVideos);
                        let promiseArr = [];
                        polyvVideos.forEach(downloadInfo => {
                            let tempPro = function () {
                                return new Promise((resolve, reject) => {
                                    new SingleDownloadTask(downloadInfo, function () {
                                        resolve("polyvVideos  success");
                                    })
                                })
                            }
                            promiseArr.push(tempPro);
                        });
                        let gen = GeneratorFactory.createGenerator(promiseArr);
                        let executor = new GeneratorExecutor();
                        executor.runSingleWithTimeOut(gen, 60, function () {
                            if (callback) { callback(); }
                            console.log("保利威视视频key同步完成...")
                        }, function (progress) {
                            if (progressCallback) {
                                if (progress) {
                                    progressCallback(parseInt((progress * 100 / polyvVideos.length).toFixed()));
                                }
                            }
                        });
                    } else {
                        if (callback) { callback(); }
                    }
                }).catch(err => {
                    if (pptThumbs.length > 0) {
                        let tempThumbs = [];
                        pptThumbs.forEach(thumbs => {
                            if (thumbs.thumbStr) {
                                tempThumbs.push(thumbs.thumbStr);
                            }
                        })
                        _this.request.getUrlByThumbs({ thumbs: tempThumbs }).then(response => {
                            if (response.code === "0") {
                                let thumbUrls = response.returnValue.thumbUrls;
                                pptThumbs.forEach(thumbs => {
                                    for (let i = 0;i < thumbUrls.length;i++) {
                                        let thumbStr = thumbUrls[i].match(/static.kquestions.com\/(\S*)\?/)[1];
                                        if (thumbs.thumbStr === thumbStr) {
                                            thumbs.thumb = thumbUrls[i];
                                            break;
                                        }
                                    }
                                })
                                console.log("下载的thumb数据pptThumbs", pptThumbs);
                                ThumbDownloader.downloadPptThumbs(pptThumbs);
                            }
                        });
                    }
                    if (polyvVideos.length > 0) {
                        console.log("polyvVideos", polyvVideos);
                        let promiseArr = [];
                        polyvVideos.forEach(downloadInfo => {
                            let tempPro = function () {
                                return new Promise((resolve, reject) => {
                                    new SingleDownloadTask(downloadInfo, function () {
                                        resolve("polyvVideos  success");
                                    })
                                })
                            }
                            promiseArr.push(tempPro);
                        });
                        let gen = GeneratorFactory.createGenerator(promiseArr);
                        let executor = new GeneratorExecutor();
                        executor.runSingleWithTimeOut(gen, 60, function () {
                            if (callback) { callback(); }
                            console.log("保利威视视频key同步完成...")
                        }, function (progress) {
                            if (progressCallback) {
                                if (progress) {
                                    progressCallback(parseInt((progress * 100 / polyvVideos.length).toFixed()));
                                }
                            }
                        });
                    } else {
                        if (callback) { callback(); }
                    }
                })
            }).catch(e => { })
        } else {
            if (callback) { callback(); }
        }
    }

    removeOldBakup () {
        if (fs.existsSync(this.oldVersionBak)) {
            try {
                fs.renameSync(this.oldVersionBak, this.oldVersionBak + ".bak")
            } catch (e) {
                fs.renameSync(this.oldVersionBak, this.oldVersionBak + ".bak")
            }
        }
    }

    checkResourceExsist (resource) {
        if (resource.downloadInfo.FileType === "courseware") {
            if (resource.downloadInfo.FileName) {
                return fs.existsSync(path.join(this.dataDir, "resc", "courseware", resource.downloadInfo.FileName))
            } else {
                console.log(resource)
                return false;
            }
        } else {
            if (resource.downloadInfo.FileType && resource.downloadInfo.TaskId) {
                return fs.existsSync(path.join(this.dataDir, "resc", resource.downloadInfo.FileType, resource.downloadInfo.TaskId))
            } else {
                console.log(resource)
                return false;
            }
        }
    }
}
